const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

// 删除旧的导入代码
// 导出初始化函数模式
module.exports = (sequelize, DataTypes) => {
    const OrderItem = sequelize.define('OrderItem', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        orderId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'orders',
                key: 'id'
            }
        },
        productId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'products',
                key: 'id'
            }
        },
        productName: {
            type: DataTypes.STRING(200),
            allowNull: false
        },
        productSku: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        productImage: {
            type: DataTypes.STRING(255),
            allowNull: true
        },
        quantity: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                min: {
                    args: 1,
                    msg: '数量必须大于0'
                }
            }
        },
        unitPrice: {
            type: DataTypes.DECIMAL(10, 2),
            allowNull: false,
            validate: {
                // 修改验证规则，使用自定义验证函数替代min验证器
                isNonNegative(value) {
                    if (parseFloat(value) < 0) {
                        throw new Error('单价不能为负数');
                    }
                }
            }
        },
        totalPrice: {
            type: DataTypes.DECIMAL(10, 2),
            allowNull: false,
            validate: {
                // 修改验证规则，使用自定义验证函数替代min验证器
                isNonNegative(value) {
                    if (parseFloat(value) < 0) {
                        throw new Error('总价不能为负数');
                    }
                }
            }
        }
    }, {
        tableName: 'order_items',
        timestamps: true,
        indexes: [
            {
                fields: ['orderId']
            },
            {
                fields: ['productId']
            }
        ]
    });

    return OrderItem;
};